package validate;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 *
 */
public class ValidatorUtil {


    private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory();

    /**
     * 请求参数非空、格式验证，请求对象
     *
     * @param object 请求校验参数
     */
    public static void validateObject(Object object) {
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<Object>> violations = validator.validate(object);
        if (!violations.isEmpty()) {
            throw new IllegalArgumentException(violations.iterator().next().getMessage());
        }
    }



    /**
     * 请求参数非空、格式验证，请求对象
     *
     * @param object 请求校验参数
     */
    public static <T> void validateObject(Object object, Class type) throws Exception {
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<Object>> violations = validator.validate(object, type);
        if (!violations.isEmpty()) {
            throw new IllegalArgumentException(violations.iterator().next().getMessage());
        }
    }



}
